package com.enation.pangu.task.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.enation.pangu.model.Step;
import com.enation.pangu.monitor.MonitorService;
import com.enation.pangu.ssh.SshClient;
import com.enation.pangu.task.StepExecutor;
import com.enation.pangu.utils.StringUtil;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;

/**
 * mysql命令执行器
 * @author kingapex
 * @version 1.0
 * @data 2022/7/4 20:27
 **/
@Service("mysql_command")
public class MysqlStepExecutor  implements StepExecutor {

    Logger logger= LoggerFactory.getLogger(MysqlStepExecutor.class);
    @Autowired
    private MonitorService monitorService;
    @Override
    public boolean execute(Step step, Map env, SshClient sshClient) {
        String executorParams =step.getExecutorParams();
        if (StringUtil.notEmpty(executorParams)) {
            Map<String, String> param = (Map<String, String>) JSONUtils.parse(executorParams);

            try {
                executeSql(param);
            } catch (Exception e) {
                e.printStackTrace();
                monitorService.appendMachineLog("sql文件执行出错");

                logger.error("mysql sql execute error",e);
                return false;
            }

        }

        return true;
    }


    private void executeSql(Map<String, String> param) throws SQLException, FileNotFoundException {
        String host = param.get("host");
        String port = param.get("port");
        String username = param.get("username");
        String password = param.get("password");
        String database = param.get("database");
        String sqlfile = param.get("sqlfile");

        //Registering the Driver
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        //Getting the connection
        String mysqlUrl = "jdbc:mysql://"+host+":"+port+"/"+database;
        Connection con = DriverManager.getConnection(mysqlUrl, username, password);
        monitorService.appendMachineLog("数据库连接成功");
        //Initialize the script runner
        ScriptRunner sr = new ScriptRunner(con);
        //Creating a reader object
        Reader reader = new BufferedReader(new FileReader(sqlfile));
        //Running the script
        sr.runScript(reader);

        monitorService.appendMachineLog("sql文件执行成功");

    }

    public static void main(String args[]) throws Exception {
        //Registering the Driver
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        //Getting the connection
        String mysqlUrl = "jdbc:mysql://192.168.2.186:3306/sbc_trade";
        Connection con = DriverManager.getConnection(mysqlUrl, "root", "123456");
        System.out.println("Connection established......");
        //Initialize the script runner
        ScriptRunner sr = new ScriptRunner(con);
        //Creating a reader object
        Reader reader = new BufferedReader(new FileReader("/Users/kingapex/database/test.sql"));
        //Running the script
        sr.runScript(reader);
    }


}
